import type { ProFormInstance } from '@/components/Pro/';
import {
  ProForm,
  ProFormDatePicker,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
} from '@/components/Pro/';
import Tabs, { TabsProps } from '@/components/Tabs';
import { CAPACITY_UNIT, getSystemElectricityPriceType, POWER_UNIT } from '@/dictionary';
import { stationControllerSaveBaseConfig as edit } from '@/services/ess/station';
import { Button, Flex, message, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess, useIntl } from 'umi';
import Styles from '../index.less';
import MapComponent from './Bmap';
import Device, { ToolBarRender as DeviceToolBarRender } from './Device';
import ElectricityPrice, { ToolBarRender } from './ElectricityPrice';
import TempCollectePoint from './TempCollectePoint';

const BaseParam: React.FC<{
  detailInfo?: API.StationInfo;
  disableEdit?: boolean;
}> = ({ detailInfo, disableEdit }) => {
  const intl = useIntl();
  const formRef = useRef<ProFormInstance>();
  const WIDTH = 450;
  const LABEL_WIDTH = 160;
  const GAP = 10;
  const pointString =
    detailInfo?.point && detailInfo.point.lng !== null && detailInfo.point.lat !== null
      ? `${detailInfo.point.lng}, ${detailInfo.point.lat}`
      : '';
  useEffect(() => {
    formRef?.current?.setFieldsValue({
      ...detailInfo,
      cellConnect: detailInfo?.cellConnect?.toString(),
      capacityUnit: detailInfo?.capacityUnit || 'MWh',
      ratedPowerUnit: detailInfo?.ratedPowerUnit || 'MW',
      chargeDischargeUnit: detailInfo?.chargeDischargeUnit || 'H',
      point: pointString,
      priceType: detailInfo?.priceType?.toString(),
    });
  }, [detailInfo]);

  const [center, setCenter] = useState<{ lng: number; lat: number }>({ lng: 116.404, lat: 39.915 });
  const [showMap, setShowMap] = useState<boolean>(false);
  const [markerPosition, setMarkerPosition] = useState<{ lng: number; lat: number } | null>(null);
  const handleSelectPoint = (locationPoint: { point: { lng: number; lat: number } }) => {
    setCenter(locationPoint.point);
    //setShowMap(false); // 隐藏地图
    // 将经纬度对象转换为字符串格式
    const pointString = `${locationPoint.point.lng}, ${locationPoint.point.lat}`;

    //设置表单的 point 字段值
    formRef.current?.setFieldsValue({
      point: pointString,
    });
  };

  const toggleMap = () => {
    setShowMap(!showMap);
  };
  return (
    <ProForm
      style={{ marginTop: 10 }}
      layout="horizontal"
      labelCol={{ flex: `${LABEL_WIDTH}px` }}
      formRef={formRef}
      submitter={{
        render:
          !disableEdit &&
          ((props, doms) => (
            <div style={{ paddingLeft: LABEL_WIDTH }}>
              <Space>{doms}</Space>
            </div>
          )),
      }}
      onFinish={async (value) => {
        if (value.minSoc <= 0 || value.maxSoc <= 0) {
          message.error(
            intl.formatMessage({
              id: 'global.SOCLimit',
            }),
          );
          return;
        }
        if (value.minSoc > value.maxSoc) {
          message.error(
            intl.formatMessage({
              id: 'global.SOCUpper',
            }),
          );
          return;
        }
        const pointParts = value.point.split(',').map((part: string) => parseFloat(part.trim()));
        const point = { lng: pointParts[0], lat: pointParts[1] };
        const res = await edit({ ...detailInfo, ...value, point } as API.StationBaseReq);
        if (res.success) {
          message.success(
            intl.formatMessage({
              id: 'global.modifiedSuccess',
            }),
          );
        }
      }}
      disabled={disableEdit}
    >
      <Flex gap={40}>
        <div style={{ width: WIDTH }}>
          <ProFormDatePicker
            name="startRunTime"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.plantOperationTime',
            })}
            width={WIDTH - LABEL_WIDTH}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.siteCommissioningTime',
                }),
              },
            ]}
          />
          <Flex gap={GAP}>
            <div style={{ width: WIDTH - 110 }}>
              <ProFormDigit
                name="ratedPower"
                label={intl.formatMessage({
                  id: 'systemManagement.siteAdministrationMenu.RatedPower',
                })}
                fieldProps={{
                  precision: 4,
                  max: 1000000000,
                }}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'systemManagement.requiredFields.ratedPower',
                    }),
                  },
                ]}
              />
            </div>
            <ProFormSelect width={100} valueEnum={POWER_UNIT} name="ratedPowerUnit" />
          </Flex>
          <ProFormDigit
            name="chargeDischargeCount"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.maximumChargeDischargeTimes',
            })}
            fieldProps={{
              addonAfter: intl.formatMessage({
                id: 'siteManage.number',
              }),
              precision: 0,
              min: 1,
              max: 1000000000,
            }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.maxChargeDischargeTimes',
                }),
              },
            ]}
          />
          <ProFormText
            name="cellTempNo"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.cellTemperatureCode',
            })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.batteryTemperatureCode',
                }),
              },
            ]}
            fieldProps={{
              maxLength: 30,
            }}
          />
          <ProFormText
            name="product"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.batteryBrand',
            })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.batteryBrand' }),
              },
            ]}
            fieldProps={{
              maxLength: 30,
            }}
          />
          <ProFormDigit
            name="maxSoc"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.upperLimitOfSOC',
            })}
            fieldProps={{ addonAfter: '%' }}
            min={0}
            max={100}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.wholeStationSOCUpperLimit',
                }),
              },
            ]}
          />
          <ProFormDigit
            name="zycCount"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.numberOfMediumPressureTanks',
            })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.mediumVoltageCompartmentNumber',
                }),
              },
            ]}
            fieldProps={{
              min: 0,
              max: 99999,
            }}
          />
          <ProFormRadio.Group
            label={intl.formatMessage({ id: 'electricityPrice.electricityPriceType' })}
            name="priceType"
            valueEnum={getSystemElectricityPriceType()}
            rules={[
              {
                required: true,
                message: `${intl.formatMessage({
                  id: 'electricityPrice.electricityPriceType',
                })}${intl.formatMessage({
                  id: 'global.cannotBeEmpty',
                })}`,
              },
            ]}
          />
        </div>
        <div style={{ width: WIDTH }}>
          <Flex gap={GAP}>
            <div style={{ width: WIDTH - 110 }}>
              <ProFormDigit
                name="capacity"
                label={intl.formatMessage({
                  id: 'systemManagement.siteAdministrationMenu.plantCapacity',
                })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'systemManagement.requiredFields.siteCapacity',
                    }),
                  },
                ]}
              />
            </div>
            <ProFormSelect width={100} valueEnum={CAPACITY_UNIT} name="capacityUnit" />
          </Flex>
          <Flex gap={GAP}>
            <div style={{ width: WIDTH - 110 }}>
              <ProFormDigit
                name="chargeDischargeTime"
                label={intl.formatMessage({
                  id: 'systemManagement.siteAdministrationMenu.chargeDischargeDuration',
                })}
                fieldProps={{
                  precision: 4,
                  max: 1000000000,
                }}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'systemManagement.requiredFields.chargeDischargeDuration',
                    }),
                  },
                ]}
              />
            </div>
            <ProFormSelect
              width={100}
              valueEnum={{
                H: {
                  text: intl.formatMessage({
                    id: 'global.hourUnit',
                  }),
                },
                M: {
                  text: intl.formatMessage({
                    id: 'global.minuteUnit',
                  }),
                },
              }}
              name="chargeDischargeUnit"
            />
          </Flex>
          <Flex gap={GAP}>
            <div style={{ width: (WIDTH - LABEL_WIDTH - 30) / 2 + LABEL_WIDTH }}>
              <ProFormDigit
                name="batteryType1"
                label={intl.formatMessage({
                  id: 'systemManagement.siteAdministrationMenu.batteryType',
                })}
                fieldProps={{
                  addonAfter: 'C',
                  precision: 2,
                  min: 0.01,
                  max: 1000000000,
                }}
                tooltip="电池的充放电能力倍率，仅支持数字;电池的容量，仅支持数字"
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'systemManagement.requiredFields.batteryChargeDischargeRate',
                    }),
                  },
                ]}
              />
            </div>
            <span style={{ fontSize: 20 }}>-</span>
            <div style={{ width: (WIDTH - LABEL_WIDTH - 30) / 2 }}>
              <ProFormDigit
                name="batteryType2"
                fieldProps={{
                  addonAfter: 'Ah',
                  precision: 0,
                  min: 1,
                  max: 1000000000,
                }}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'systemManagement.requiredFields.batteryCapacity',
                    }),
                  },
                ]}
              />
            </div>
          </Flex>
          <ProFormDigit
            name="clusterRatedCapacity"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.clusterRatedAh',
            })}
            fieldProps={{
              addonAfter: 'Ah',
              min: 0,
              max: 1000000000,
            }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.neddTochange.clusterRatedAhRequired',
                }),
              },
              () => ({
                validator(_, value) {
                  if (value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(
                    intl.formatMessage({
                      id: 'systemManagement.requiredFields.inputValueGreaterThanZero',
                    }),
                  );
                },
              }),
            ]}
          />
          <ProFormText
            name="address"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.powerPlantAddress',
            })}
            fieldProps={{
              maxLength: 200,
            }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.powerPlantAddress',
                }),
              },
            ]}
          />
          <ProFormText
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.plantLatitudeAndLongitude',
            })}
            name="point"
            rules={[
              {
                required: false,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.siteAddress' }),
              },
            ]}
            fieldProps={{
              placeholder: intl.formatMessage({
                id: 'systemManagement.requiredFields.markSiteLocation',
              }),
              addonAfter: (
                <Button
                  type="link"
                  shape="circle"
                  className={Styles.locationButton}
                  onClick={toggleMap}
                >
                  {intl.formatMessage({
                    id: 'systemManagement.siteAdministrationMenu.selectLocation',
                  })}
                </Button>
              ),
              // addonAfter: formatMessage({ id: 'component.button.signature' })
            }}
            disabled
          />
          {showMap && (
            <MapComponent
              center={center}
              onSelectPoint={handleSelectPoint}
              markerPosition={markerPosition}
              setMarkerPosition={setMarkerPosition}
            />
          )}
          <ProFormDigit
            name="minSoc"
            label={intl.formatMessage({
              id: 'systemManagement.siteAdministrationMenu.lowerLimitOfSOCForTheEntirePlant',
            })}
            fieldProps={{ addonAfter: '%' }}
            min={0}
            max={100}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'systemManagement.requiredFields.wholeStationSOCLowerLimit',
                }),
              },
            ]}
          />
        </div>
      </Flex>
    </ProForm>
  );
};

const ParamConfig: React.FC<{
  detailInfo: API.StationInfo;
  id: string | number;
  className?: string;
  disableEdit?: boolean;
}> = ({ detailInfo, id, disableEdit }) => {
  const access = useAccess();
  const electricityPriceRef = useRef(null);
  const deviceRef = useRef(null);
  const intl = useIntl();

  let items: TabsProps['items'] = [];

  const tab1 = {
    key: '1',
    label: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.Basicparameters' }),
    children: <BaseParam detailInfo={detailInfo} disableEdit={disableEdit} />,
  };

  const tab2 = {
    key: '2',
    label: intl.formatMessage({
      id: 'systemManagement.siteAdministrationMenu.electricityPriceParameters',
    }),
    children: <ElectricityPrice ref={electricityPriceRef} id={id} disableEdit={disableEdit} />,
  };

  const tab3 = {
    key: '3',
    label: intl.formatMessage({
      id: 'systemManagement.siteAdministrationMenu.batteryTemperatureCollectionPoint',
    }),
    children: <TempCollectePoint id={id} disableEdit={disableEdit} />,
  };

  const tab4 = {
    key: '4',
    label: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.deviceInformation' }),
    children: <Device ref={deviceRef} id={id} disableEdit={disableEdit} />,
  };

  // 查看详情
  if (disableEdit) {
    //设备信息已经挪到设备管理 tab4 不做显示
    items = [tab1, tab2, tab3];
  } else {
    if (access.can('sys:station:paramConf:base')) {
      items.push(tab1);
    }
    // if (access.can('sys:station:paramConf:price')) {
    //   items.push(tab2);
    // }
    if (access.can('sys:station:paramConf:TempColPoint')) {
      items.push(tab3);
    }
    if (access.can('sys:station:paramConf:device')) {
      items.push(tab4);
    }
  }

  const [activeKey, setActiveKey] = useState(items?.[0]?.key);

  const onChange = (key: string) => {
    setActiveKey(key);
  };

  return (
    <Tabs
      activeKey={activeKey}
      items={items}
      onChange={onChange}
      tabBarExtraContent={
        (activeKey === '2' && !disableEdit && <ToolBarRender tableRef={electricityPriceRef} />) ||
        (activeKey === '4' && !disableEdit && <DeviceToolBarRender tableRef={deviceRef} />)
      }
      tabsLevel={2}
    />
  );
};
export default ParamConfig;
